//
//  WeatherView.m
//  iCarStyle
//
//  Created by liunian on 13-9-5.
//  Copyright (c) 2013年 liunian. All rights reserved.
//

#import "WeatherView.h"
#import "FMDatabase.h"
#import "FMResultSet.h"
#import "FMDatabaseAdditions.h"
#import "MKImageView.h"
#import "AdItem.h"
#import "CSCoverStoryManager.h"
#import <QuartzCore/QuartzCore.h>
#import "UIImageView+WebCache.h"
#import "CSCoverStoryManager.h"
#import "DataEnvironment.h"
#import "JSONKit.h"
#import "RootViewController.h"
#import "ADWebViewController.h"

#define kBeijingWeatherAPI  @"http://www.weather.com.cn/data/cityinfo/101010100.html"


#define kTagStoryView   102121
static const int kIntAnimationInterval = 30;
static const int kIntSwitchImageInterval = kIntAnimationInterval+3;
static const int kIntSwitchActionDuration = 2;

@implementation Weatherinfo

- (id)initWithDict:(NSDictionary *)dict{
    self = [super init];
    if (self) {
        self.city = [dict objectForKey:@"city"];
        self.tempH = [dict objectForKey:@"temp1"];
        self.tempL = [dict objectForKey:@"temp2"];
        self.weather = [dict objectForKey:@"weather"];
        self.ptime = [dict objectForKey:@"ptime"];
    }
    return self;
}

@end
@interface WeatherView ()<CLLocationManagerDelegate,CSCoverStoryManagerDelegate>{
    CGPoint   _startPoint;
    NSInteger _coverIndex;
}
@property (nonatomic, strong) CLLocationManager *locManager;
@property (nonatomic, strong) UILabel   *city;
@property (nonatomic, strong) UILabel   *temp;
@property (nonatomic, strong) UILabel   *tempH;
@property (nonatomic, strong) UILabel   *tempL;
@property (nonatomic, strong) UILabel   *weather;
@property (nonatomic, strong) Weatherinfo *weatherinfo;

@property (nonatomic, retain) UIView *imageViewFrame;
@property (nonatomic, retain) MKImageView *imageView;
@property (nonatomic, retain) MKImageView *nextImageView;
@property (nonatomic, retain) AdItem   *curAdItem;
@property (nonatomic, retain) UIImageView *arrowImageView;
@property (nonatomic, retain) UIView *storyView;

- (void)showArrow;
- (void)startAnimation;
- (void)stopAnimation;
- (void)selectNextImage;
- (void)resetNextImageFrame;
- (void)switchImageActionDone;

- (void)showCoverImage;

- (void)storyButtonTapped:(id)sender;
@end

@implementation WeatherView

- (void)dealloc{
    [[CSCoverStoryManager sharedManager] removeObserver:self];
}

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        [self setBackgroundColor:[UIColor blackColor]];
        _showDefault = NO;
        _coverIndex = 0;
        
        [[CSCoverStoryManager sharedManager] addObserver:self];
        [[CSCoverStoryManager sharedManager] requestAD];
        [self showCoverImage];
        
        [self performSelector:@selector(showArrow) withObject:nil afterDelay:1.0f];
        
        [self.locManager startUpdatingLocation];
    }
    return self;
}

- (void)requestWeatherWithCityCode:(NSString *)city{
    [self storeCityCode:city];
    NSString *weatherString = nil;
    NSString * string1 = @"http://www.weather.com.cn/data/cityinfo/";
    NSString * string3 = @".html";
    weatherString = @"";
    weatherString = [weatherString stringByAppendingFormat:@"%@%@%@",string1,city,string3];

    NSURL *url1 = [NSURL URLWithString:weatherString];
    NSURLRequest *request1 = [[NSURLRequest alloc]initWithURL:url1 cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];
    NSData *received1 = [NSURLConnection sendSynchronousRequest:request1 returningResponse:nil error:nil];
    if ([received1 length] <=0) {
        return;
    }
    JSONDecoder * jd = [[JSONDecoder alloc]init];
    NSDictionary * result = [jd objectWithData:received1];
    NSDictionary *info = [result objectForKey:@"weatherinfo"];
    if (info) {
        dispatch_async(dispatch_get_main_queue(), ^{
            self.weatherinfo = [[Weatherinfo alloc] initWithDict:info];
        });
    }

}

- (void)getCityCodeWithCityName:(NSString *)cityName{
    NSString *finalCityName = nil;
    NSString *name22 = nil;
    NSString *number22 = nil;
    NSString * cityName22 = nil;
    NSString * cityNumber = nil;
    NSString * string2 = nil;//城市号码
    NSString *name1 = cityName;
    
    finalCityName = [name1 substringToIndex:(unsigned long)[name1 length]-1];
    finalCityName = name1;
    //寻找路径
    NSString *doc_path=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0];
    //数据库路径
    NSString *sqlPath=[doc_path stringByAppendingPathComponent:@"cityname.sqlite"];
    
    //原始路径
    NSString *orignFilePath = [[NSBundle mainBundle] pathForResource:@"cityname" ofType:@"sqlite"];
    
    NSFileManager *fm = [NSFileManager defaultManager];
    if([fm fileExistsAtPath:sqlPath] == NO)//如果doc下没有数据库，从bundle里面拷贝过来
    {
        NSError *err = nil;
        if([fm copyItemAtPath:orignFilePath toPath:sqlPath error:&err] == NO){
            BMLog(@"open database error %@",[err localizedDescription]);
        }
    }
    //初始化数据库
    FMDatabase *db=[FMDatabase databaseWithPath:sqlPath];
    //这个方法一定要执行
    if (![db open]) {
    }
    FMResultSet *resultSet=[db executeQuery:@"select * from citys"];
    while ([resultSet next]) {
        name22 = [resultSet stringForColumn:@"Name"];
        number22 = [resultSet stringForColumn:@"city_num"];
        NSArray *nameArray = [name22 componentsSeparatedByString:@"."];
        if (name22.length<5) {
            cityName22 = name22;
            if ([cityName22 isEqualToString: name1 ]) {
                cityNumber = number22;
            }
        }else{
            cityName22 = [nameArray objectAtIndex:1];
            
            if ([cityName22  isEqualToString: name1 ]) {
                cityNumber = number22;
            }
        }
    }
    [db close];
    
    if (cityNumber == NULL) {
        string2 = @"101010100";
    }else{
        string2 = cityNumber;
    }
    [self requestWeatherWithCityCode:string2];
}

- (void)requestAndPaserWeather{
    NSString *cityName = @"北京市";
    NSString *currentLatitude = [[NSString alloc]
                                 initWithFormat:@"%g",
                                 self.locManager.location.coordinate.latitude];
    NSString *currentLongitude = [[NSString alloc]
                                  initWithFormat:@"%g",
                                  self.locManager.location.coordinate.longitude];
    NSString * str1 = @"http://maps.google.com/maps/api/geocode/json?latlng=";
    NSString * str2 = @",";
    NSString * str3 = @"&language=zh-CN&sensor=true";
    NSString * string = @"";
    string = [string stringByAppendingFormat:@"%@%@%@%@%@",str1,currentLatitude,str2,currentLongitude,str3];
    NSURL *url = [NSURL URLWithString:string];

    NSURLRequest *request = [[NSURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];
    NSData *received = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    NSString *citystring = [[NSString alloc]initWithData:received encoding:NSUTF8StringEncoding];
    
    NSDictionary  *jsonDict = [citystring objectFromJSONString];
    if (isDictWithCountMoreThan0(jsonDict)) {
        if ([[jsonDict objectForKey:@"status"] isEqualToString:@"OK"]) {
            NSArray *results = [jsonDict objectForKey:@"results"];
            if (isArrayWithCountMoreThan0(results)) {
                if (results.count > 0) {
                    
                    NSDictionary *address = [results objectAtIndex:0];
                    if (isDictWithCountMoreThan0(address)) {
                        NSArray *address_components = [address objectForKey:@"address_components"];
                        if (isArrayWithCountMoreThan0(address_components)) {
                            
                            for (NSDictionary *dic in address_components) {
                                NSArray *types = [dic objectForKey:@"types"];
                                if ([[types objectAtIndex:0] isEqualToString:@"locality"]) {
                                    cityName = [dic objectForKey:@"long_name"];
                                }
                                
                            }
                        }
                    }
                    
                }
            }
        }
    }
    [self getCityCodeWithCityName:cityName];
}

- (void)locationDone{
    
    if ([self cityCode]) {
        [self requestWeatherWithCityCode:[self cityCode]];
    }
    
    dispatch_async(kBgQueue, ^{
        [self requestAndPaserWeather];
    });
}

#define kCITYCODE   @"cityCode"
- (void)storeCityCode:(NSString *)cityCode{
    if ([cityCode isEqualToString:@"101010100"]) {
        return;
    }
    [[NSUserDefaults standardUserDefaults] setObject:cityCode forKey:kCITYCODE];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

- (NSString *)cityCode{
    NSString *cityCode = nil;
    cityCode = [[NSUserDefaults standardUserDefaults] objectForKey:kCITYCODE];
    return cityCode;
}

- (void)updateWithWeatherInfo{
    [self.city setText:self.weatherinfo.city];
    [self.temp setText:self.weatherinfo.tempH];
    [self.tempH setText:[NSString stringWithFormat:@"H  %@",self.weatherinfo.tempH]];
    [self.tempL setText:[NSString stringWithFormat:@"L  %@",self.weatherinfo.tempL]];
    [self.weather setText:self.weatherinfo.weather];
}


#pragma mark CLLocationManagerDelegate
//定位时候调用
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation{
    dispatch_async(kBgQueue, ^{
        [self locationDone];
    });
    [self.locManager stopUpdatingLocation];
}

//定位出错时被调
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{
    
}

- (void)layoutSubviews {
    [super layoutSubviews];
}

- (void)showArrow {
    [self.arrowImageView startAnimating];
	self.arrowImageView.alpha = 0;
	self.arrowImageView.layer.transform = CATransform3DMakeScale(2.0, 2.0, 1.0);
	[UIView beginAnimations:nil context:nil];
	[UIView setAnimationDuration:1];
	[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
	self.arrowImageView.alpha = 1;
	self.arrowImageView.layer.transform = CATransform3DMakeScale(1.0, 1.0, 1.0);
	[UIView commitAnimations];
}

#pragma mark - Image Animation
- (void)startImageSwitch {
    if (!self.imageView.adItem) {
        if (self.frame.origin.x == 0) {
            [self startAnimation];
        }
    }
    
    INVALIDATE_TIMER(_switchTimer);
    _switchTimer = [NSTimer scheduledTimerWithTimeInterval:5
                                                     target:self
                                                   selector:@selector(selectNextImage)
                                                   userInfo:nil
                                                    repeats:NO];
}

- (void)stopImageSwitch {
    if (!self.imageView.adItem) {
        [self stopAnimation];
    }
    INVALIDATE_TIMER(_switchTimer);
}

- (void)startAnimation {
    CGSize size;
    size.width = self.imageView.frame.size.width;
    size.height = self.imageView.frame.size.height;
    
    CGMutablePathRef path = CGPathCreateMutable();
    CGPathMoveToPoint(path, NULL, _startPoint.x,_startPoint.y);
    if (fabs(_startPoint.x-self.bounds.size.width/2)>10.0 ||
        fabs(_startPoint.y-self.bounds.size.height/2)>10.0) {
        CGPathAddLineToPoint(path, NULL, floor(self.bounds.size.width/2), floor(self.bounds.size.height/2));
    }
    _startPoint = CGPointMake(floor(self.bounds.size.width/2), floor(self.bounds.size.height/2));
    
    CGPathAddLineToPoint(path, NULL, floor(self.bounds.size.width-size.width/2), floor(self.bounds.size.height-size.height/2));
    CGPathAddLineToPoint(path, NULL, floor(self.bounds.size.width-size.width/2), size.height/2);
    CGPathAddLineToPoint(path, NULL, floor(self.bounds.size.width/2), floor(self.bounds.size.height/2));
    CGPathAddLineToPoint(path, NULL, floor(size.width/2), floor(self.bounds.size.height-size.height/2));
    CGPathAddLineToPoint(path, NULL, floor(size.width/2), floor(size.height/2));
    CGPathAddLineToPoint(path, NULL, floor(self.bounds.size.width/2), floor(self.bounds.size.height/2));
    
    CAKeyframeAnimation *pathAnimation = [CAKeyframeAnimation animationWithKeyPath:@"position"];
    [pathAnimation setPath:path];
    pathAnimation.duration = kIntAnimationInterval;
    pathAnimation.removedOnCompletion = YES;
    CFRelease(path);
    [self.imageView.layer addAnimation:pathAnimation forKey:@"CoverPositionAnimation"];
    
    self.imageView.layer.position = CGPointMake(floor(self.bounds.size.width/2), floor(self.bounds.size.height/2));
}

- (void)stopAnimation {
    if ([self.imageView.layer animationForKey:@"CoverPositionAnimation"]) {
        _startPoint = [(CALayer *)[self.imageView.layer presentationLayer] position];
        [self.imageView.layer removeAnimationForKey:@"CoverPositionAnimation"];
        
        self.imageView.layer.position = _startPoint;
    }
}

#pragma mark - Image Switch
- (void)resetNextImageFrame
{
    CGFloat maxScaleH = 1.5f;
    CGFloat maxScaleV = 1.4f;
    CGFloat scale = 1.1f;
    
    CGSize size = self.nextImageView.image.size;
    //    if (size.width > self.bounds.size.width*scale && size.height > self.bounds.size.height*scale)
    {
        CGFloat ratio1 = (self.bounds.size.width*scale)/size.width;
        CGFloat ratio2 = (self.bounds.size.height*scale)/size.height;
        if (ratio1 > ratio2) {
            size.width = size.width*ratio1;
            size.height = size.height*ratio1;
            if (size.height > self.bounds.size.height*maxScaleV) {
                size.height = self.bounds.size.height*maxScaleV;
            }
        } else {
            size.width = size.width*ratio2;
            size.height = size.height*ratio2;
            if (size.width > self.bounds.size.width*maxScaleH) {
                size.width = self.bounds.size.width*maxScaleH;
            }
        }
    }
    self.nextImageView.frame = CGRectMake(0, 0, size.width, size.height);
    self.nextImageView.center = self.imageViewFrame.center;
}


static inline UIViewAnimationOptions animationOptionsWithCurve(UIViewAnimationCurve curve)
{
    switch (curve) {
        case UIViewAnimationCurveEaseInOut:
            return UIViewAnimationOptionCurveEaseInOut;
        case UIViewAnimationCurveEaseIn:
            return UIViewAnimationOptionCurveEaseIn;
        case UIViewAnimationCurveEaseOut:
            return UIViewAnimationOptionCurveEaseOut;
        case UIViewAnimationCurveLinear:
            return UIViewAnimationOptionCurveLinear;
    }
}


- (void)switchImageAction {
    [self stopAnimation];
    _startPoint = CGPointMake(floor(self.bounds.size.width/2), floor(self.bounds.size.height/2));
    
	//图片切换动画
    self.nextImageView.alpha = 0.0f;
	_imageView.alpha = 1.0f;
    
    UIView *oldStoryView = [self viewWithTag:kTagStoryView];
    
    self.storyView.alpha = 0.0f;
    [self addSubview:self.storyView];
    [self bringSubviewToFront:_arrowImageView];
    [UIView animateWithDuration:kIntSwitchActionDuration
                          delay:0.0
                        options:animationOptionsWithCurve(UIViewAnimationCurveEaseInOut)
                     animations:^{
                         self.nextImageView.alpha = 1.0f;
                         self.storyView.alpha = 0.7f;
                         self.imageView.alpha = 0.0f;
                         oldStoryView.alpha = 0.0f;
                     }
                     completion:^(BOOL finished) {
                         [oldStoryView removeFromSuperview];
                         self.storyView = nil;
                         [self switchImageActionDone];
                     }];
}

- (void)switchImageActionDone {
	
    MKImageView *tmp = self.imageView;
    self.imageView = self.nextImageView;
    self.nextImageView = tmp;
    
    if (!_imageView.adItem) {
        if (self.frame.origin.x == 0) {
            [self startAnimation];
        }
    }
    
    NSTimeInterval interval = kIntSwitchImageInterval;
    if (_imageView.adItem) {
        interval = floor(kIntSwitchImageInterval/2);
    } else if (_showDefault) {
        interval = 5;
    }
    _switchTimer = [NSTimer scheduledTimerWithTimeInterval:interval
                                                     target:self
                                                   selector:@selector(selectNextImage)
                                                   userInfo:nil
                                                    repeats:NO];
    
}

- (void)selectNextImage
{
    INVALIDATE_TIMER(_switchTimer);
    self.curAdItem = nil;
    
    if (!_imageView || !_imageView.image) {
        self.nextImageView.adItem = nil;
        self.nextImageView.image = IMGNAMED(@"cover.jpg");
        [self resetNextImageFrame];
        _showDefault = YES;
        [self switchImageAction];
        
        return;
    }
    
    NSMutableArray *array = [NSMutableArray arrayWithCapacity:0];
    if ([CSCoverStoryManager sharedManager].ads) {
        [array addObjectsFromArray:[CSCoverStoryManager sharedManager].ads];
    }
    
    if ([array count] == 0) {
        if (!_showDefault) {
            self.nextImageView.adItem = nil;
            self.nextImageView.image = IMGNAMED(@"cover.jpg");
            [self resetNextImageFrame];
            _showDefault = YES;
            [self switchImageAction];
        } else {
            _switchTimer = [NSTimer scheduledTimerWithTimeInterval:kIntSwitchImageInterval
                                                             target:self
                                                           selector:@selector(selectNextImage)
                                                           userInfo:nil
                                                            repeats:NO];
        }
        
    } else {
        
        if (_coverIndex >=[array count] || _coverIndex < 0) {
            _coverIndex = 0;
        }
        
        NSObject *object = [array objectAtIndex:_coverIndex];
        
        if ([object isKindOfClass:[AdItem class]]) {
            AdItem *adItem = (AdItem *)object;
            self.nextImageView.adItem = adItem;
            self.curAdItem = adItem;
            
            __block WeatherView *weatherView = self;
            [self.nextImageView setImageWithURL:[NSURL URLWithString:adItem.adUrl] placeholderImage:IMGNAMED(@"") completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType) {
                if (image) {
                    [weatherView doneFinishImage];
                }
                
                if (error) {
                    [weatherView performSelector:@selector(selectNextImage) withObject:nil afterDelay:10.0f];
                }
                
            }];
        }
        
        _coverIndex++;
    }
}

- (void)doneFinishImage{
    _showDefault = NO;
    if ([_imageView adItem]) {
        _nextImageView.frame = self.imageViewFrame.bounds;
    } else {
        [self resetNextImageFrame];
    }
    [self switchImageAction];
}

#pragma mark - Show AD
- (void)showCoverImage
{
    [self selectNextImage];
}

#pragma mark CSCoverStoryManagerDelegate
- (void)mkManagerAllAdsRequestDidFinishedWithAds:(NSArray *)ads{
    _coverIndex = 0;
    [self selectNextImage];
}


#pragma mark - UIButton method
- (void)storyButtonTapped:(id)sender {
    if (self.curAdItem) {
        NSString *clickTypeStr = @"";
        if (self.curAdItem.clickType == MKAdClickTypeApp) {
            clickTypeStr = @"App";
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:self.curAdItem.clickUrl]];
            
        } else if (self.curAdItem.clickType == MKAdClickTypeUrl) {
            clickTypeStr = @"Url";
            if (self.curAdItem.clickUrl) {
                ADWebViewController *webViewController = [[ADWebViewController alloc] initWithURL:[NSURL URLWithString:self.curAdItem.clickUrl]];
                [[DataEnvironment sharedDataEnvironment].rootViewController presentViewController:webViewController animated:YES completion:nil];
            }
        }
        [[DataEnvironment sharedDataEnvironment].rootViewController hideCover];
        

        NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
                              self.curAdItem.title, @"title",self.curAdItem.clickUrl, @"clickUrl",clickTypeStr,@"clickType", nil];
        [MobClick event:@"coverClick" attributes:dict];
    }
}

#pragma mark setter
- (void)setWeatherinfo:(Weatherinfo *)weatherinfo{
    if (weatherinfo) {
        _weatherinfo = weatherinfo;
        [self updateWithWeatherInfo];
    }
}
#define kShadowOffset CGSizeMake(0, 1.0)
#pragma mark
- (CLLocationManager *)locManager{
    if (nil== _locManager) {
        _locManager = [[CLLocationManager alloc] init];
        _locManager.delegate = self;
        _locManager.desiredAccuracy = kCLLocationAccuracyBest;
        _locManager.distanceFilter = 1000.0f;
    }
    return _locManager;
}

- (UILabel *)city{
    if (!_city) {
        _city = [[UILabel alloc] initWithFrame:CGRectMake(20, 20, 200, 30)];
        [_city setFont:[UIFont systemFontOfSize:22]];
        [_city setBackgroundColor:[UIColor clearColor]];
        [_city setTextColor:[UIColor whiteColor]];
        
        _city.shadowColor = [UIColor flatGrayColor];
        _city.shadowOffset = kShadowOffset;
        [self addSubview:_city];
    }
    return _city;
}

- (UILabel *)temp{
    if (!_temp) {
        _temp = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMinX(self.city.frame), 60, 120, 40)];
        [_temp setFont:[UIFont boldSystemFontOfSize:48]];
        [_temp setBackgroundColor:[UIColor clearColor]];
        [_temp setTextColor:[UIColor whiteColor]];
        
        _temp.shadowColor = [UIColor flatGrayColor];
        _temp.shadowOffset = kShadowOffset;
        [self addSubview:_temp];
    }
    return _temp;
}

- (UILabel *)tempH{
    if (!_tempH) {
        _tempH = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(self.temp.frame), CGRectGetMinY(self.temp.frame), 160, 20)];
        [_tempH setFont:[UIFont systemFontOfSize:14]];
        [_tempH setBackgroundColor:[UIColor clearColor]];
        [_tempH setTextColor:[UIColor flatWhiteColor]];
        
        _tempH.shadowColor = [UIColor flatGrayColor];
        _tempH.shadowOffset = kShadowOffset;
        [self addSubview:_tempH];
    }
    return _tempH;
}

- (UILabel *)tempL{
    if (!_tempL) {
        _tempL = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMinX(self.tempH.frame), CGRectGetMaxY(self.tempH.frame), 160, 20)];
        [_tempL setFont:[UIFont systemFontOfSize:14]];
        [_tempL setBackgroundColor:[UIColor clearColor]];
        [_tempL setTextColor:[UIColor flatWhiteColor]];
        
        _tempL.shadowColor = [UIColor flatGrayColor];
        _tempL.shadowOffset = kShadowOffset;
        [self addSubview:_tempL];
    }
    return _tempL;
}

- (UILabel *)weather{
    if (!_weather) {
        _weather = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMinX(self.temp.frame), CGRectGetMaxY(self.temp.frame), 200, 30)];
        [_weather setFont:[UIFont systemFontOfSize:22]];
        [_weather setBackgroundColor:[UIColor clearColor]];
        [_weather setTextColor:[UIColor whiteColor]];
        
        _weather.shadowColor = [UIColor flatGrayColor];
        _weather.shadowOffset = kShadowOffset;
        
        [self addSubview:_weather];
    }
    return _weather;
}
- (UIView *)storyView {

    if (!self.curAdItem || !self.curAdItem.title || [self.curAdItem.title length] == 0) {
        return nil;
    }
    
    if (!_storyView) {
        _storyView = [[UIView alloc] initWithFrame:CGRectMake(floor((self.bounds.size.width-320)/2),
                                                              self.bounds.size.height-40,
                                                              320.0f, 40.0f)];
        _storyView.backgroundColor = [UIColor blackColor];
        _storyView.alpha = 0.6;
        _storyView.tag = kTagStoryView;
        _storyView.clipsToBounds = YES;
        
        UILabel *titleLabel = [[UILabel alloc] init];
        titleLabel.numberOfLines = 1;
        titleLabel.backgroundColor = [UIColor clearColor];
        titleLabel.textColor = COLOR_RGB(255.0,254.0,254.0);
        titleLabel.font = FONT_CONTENT(18.0);
        NSString *title = self.curAdItem.title;
        if ([title length]>25) {
            title = [title substringToIndex:25];
            title = [NSString stringWithFormat:@"%@...",title];
        }
        titleLabel.text = title;
        CGSize size = [titleLabel sizeThatFits:CGSizeMake(_storyView.bounds.size.width-10, CGFLOAT_MAX)];
        titleLabel.frame = CGRectMake(10, 10, size.width,20);
        [_storyView addSubview:titleLabel];
        
        UIButton *storyButton = [UIButton buttonWithType:UIButtonTypeCustom];
        storyButton.backgroundColor = [UIColor clearColor];
        [storyButton setBackgroundImage:IMGNAMED(@"bg_button_highlighted.png") forState:UIControlStateHighlighted];
        storyButton.frame = _storyView.bounds;
        [_storyView addSubview:storyButton];
        [_storyView sendSubviewToBack:storyButton];
        [storyButton addTarget:self action:@selector(storyButtonTapped:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _storyView;
}

- (MKImageView *)imageView {
    if (!_imageView) {
        _imageView = [[MKImageView alloc] initWithFrame:self.imageViewFrame.bounds];
        _imageView.backgroundColor = [UIColor clearColor];
        _imageView.contentMode = UIViewContentModeScaleAspectFill;
        
        [self.imageViewFrame addSubview:_imageView];
    }
    return _imageView;
}

- (MKImageView *)nextImageView
{
    if (!_nextImageView) {
        _nextImageView = [[MKImageView alloc] initWithFrame:self.imageViewFrame.bounds];
        _nextImageView.backgroundColor = [UIColor clearColor];
        _nextImageView.contentMode = UIViewContentModeScaleAspectFill;
        
        [self.imageViewFrame addSubview:_nextImageView];
    }
    return _nextImageView;
}


- (UIView *)imageViewFrame {
    if (!_imageViewFrame) {
        _imageViewFrame = [[UIView alloc] initWithFrame:self.bounds];
        _imageViewFrame.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
        _imageViewFrame.backgroundColor = [UIColor clearColor];
        _imageViewFrame.clipsToBounds = YES;
        [self addSubview:_imageViewFrame];
        [self sendSubviewToBack:_imageViewFrame];
    }
    return _imageViewFrame;
}

- (UIImageView *)arrowImageView {
    if (!_arrowImageView) {
        _arrowImageView = [[UIImageView alloc] initWithFrame:CGRectZero];
        UIImage *image = IMGNAMED(@"icon_arrow1.png");
        _arrowImageView.frame = CGRectMake(self.bounds.size.width-image.size.width,
                                           self.bounds.size.height-image.size.height-100,
                                           image.size.width, image.size.height);
        NSArray *imageArr = [NSArray arrayWithObjects:
                             IMGNAMED(@"icon_arrow1.png"),
                             IMGNAMED(@"icon_arrow2.png"),
                             IMGNAMED(@"icon_arrow3.png"),
                             IMGNAMED(@"icon_arrow4.png"),
                             IMGNAMED(@"icon_arrow5.png"),
                             IMGNAMED(@"icon_arrow6.png"),
                             IMGNAMED(@"icon_arrow7.png"),
                             IMGNAMED(@"icon_arrow8.png"),
                             IMGNAMED(@"icon_arrow9.png"),
                             IMGNAMED(@"icon_arrow10.png"),
                             nil];
        _arrowImageView.animationImages = imageArr;
        _arrowImageView.animationDuration = 1.5f;
        [self addSubview:_arrowImageView];
    }
    return _arrowImageView;
}
@end
